/* Copyright (c) [2025] [zhi1208@126.com]
 * SPDX-License-Identifier: MIT
 */

/*********************
 *      INCLUDES
 *********************/
#include "lvgl.h"
#include "hmi_config.h"
#include "hmi_pg_def.h"
#include "hmi_bg.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/

/**********************
 *  STATIC VARIABLES
 **********************/

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/
void hmi_anim_translate_y_exec_cb(void *var, int32_t val)
{
    lv_obj_set_style_translate_y(var, val, 0);
}

void hmi_enter_anim_default(lv_obj_t *obj, lv_anim_completed_cb_t cb, uint32_t delay)
{
    uint32_t child_cnt = lv_obj_get_child_count(obj);

    lv_anim_t a;
    lv_anim_init(&a);
    lv_anim_set_duration(&a, HMI_ANIM_TIME);
    lv_anim_set_exec_cb(&a, hmi_anim_translate_y_exec_cb);
    lv_anim_set_values(&a, -HMI_ANIM_Y, 0);
    lv_anim_set_path_cb(&a, lv_anim_path_ease_out);

    for (uint32_t i = 0; i < child_cnt; ++i)
    {
        lv_obj_t *child = lv_obj_get_child(obj, i);
        lv_anim_set_var(&a, child);
        lv_anim_set_delay(&a, delay + HMI_ANIM_DELAY * (i + 1));

        if (i == child_cnt - 1)
            lv_anim_set_completed_cb(&a, cb);

        lv_anim_start(&a);
        lv_obj_fade_in(child, HMI_ANIM_DELAY, delay + HMI_ANIM_DELAY * (i + 1));
    }
}

uint32_t hmi_exit_anim_default(lv_obj_t *obj, lv_anim_completed_cb_t cb, hmi_pg_t *enter_pg)
{
    uint32_t child_cnt = lv_obj_get_child_count(obj);

    lv_anim_t a;
    lv_anim_init(&a);
    lv_anim_set_duration(&a, HMI_ANIM_TIME);
    lv_anim_set_delay(&a, 0);
    lv_anim_set_exec_cb(&a, hmi_anim_translate_y_exec_cb);
    lv_anim_set_path_cb(&a, lv_anim_path_ease_out);

    for (uint32_t i = 0; i < child_cnt; ++i)
    {
        lv_obj_t *child = lv_obj_get_child(obj, i);
        lv_anim_set_var(&a, child);

        lv_area_t coords;
        lv_obj_get_coords(child, &coords);
        if (coords.y1 < lv_display_get_vertical_resolution(lv_display_get_default()) / 2)
            lv_anim_set_values(&a, 0, -HMI_ANIM_Y);
        else
            lv_anim_set_values(&a, 0, HMI_ANIM_Y);

        if (i == child_cnt - 1)
        {
            lv_anim_set_user_data(&a, enter_pg);
            lv_anim_set_completed_cb(&a, cb);
        }

        lv_anim_start(&a);
        lv_obj_fade_out(child, HMI_ANIM_DELAY, 0);
    }

    hmi_anim_bg(enter_pg->bg_color, enter_pg->bg_y);

    return HMI_ANIM_TIME;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/